package cn.wj.school.cloud.dubbo;

import cn.wj.school.cloud.aspect.JteachAutoLog;
import cn.wj.school.cloud.dto.Response;
import cn.wj.school.cloud.dto.SyLoginLogDTO;
import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.cloud.enums.OperateType;
import cn.wj.school.cloud.model.SyLoginLog;
import cn.wj.school.cloud.service.LoginLogService;
import cn.wj.school.cloud.service.UserService;
import cn.wj.school.cloud.utils.EncryptAlgorithm;
import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: yueding
 * @Description:
 * @Date: Created in 11:13 2019/1/14
 * @Modified By: yueding
 * Copyright(c) cai-inc.com
 */
@Service(version = "1.0.0", interfaceClass = JteachDubboService.class)
@Component
@JteachAutoLog(module = "RPC服务", tag = "JteachDubboService")
@Slf4j
public class JteachDubboServiceImpl implements JteachDubboService {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginLogService loginLogService;

    /**
     * 登录
     *
     * @param account
     * @param password
     * @return
     */
    @Override
    public Response<SyUserDTO> userLogin(String account, String password) {
        SyUserDTO user = userService.getUserByUserAccount(account);
        if (null != user && EncryptAlgorithm.hexMD5(password).equals(user.getPassword())) {

            return Response.ok(user);
        }
        return Response.fail("用户名密码错误!");
    }

    /**
     * 登出
     *
     * @param account
     * @return
     */
    @Override
    public Response<Boolean> userLoginOut(String account) {
        SyUserDTO user = userService.getUserByUserAccount(account);
        if (null != user) {

        }
        return null;
    }

    @Override
    public Response<Boolean> registerLoginInfo(Long userId, OperateType type) {
        if (userId == null) {
            return Response.fail("参数有误");
        }
        SyUserDTO user = userService.getUserByUserId(userId);
        if (user == null) {
            return Response.fail("无此用户!");
        }
        SyLoginLogDTO currentLog = loginLogService.getCurrentLog(userId);
        if (currentLog == null && OperateType.LOGIN.equals(type)) {
            currentLog = new SyLoginLogDTO();
            currentLog.setUserId(userId);
            currentLog.setUserCard(user.getCard());
            currentLog.setUserName(user.getUserName());
            currentLog.setSchool(user.getSchool());
            currentLog.setLoginTime(new Date());
            loginLogService.saveLoginLog(currentLog);
        } else if (currentLog != null
                && OperateType.LOGOUT.equals(type)) {
            loginLogService.writeLogoutTime(currentLog.getId());
        }
        return Response.ok();
    }
}
